﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace RabbitMQ.Servers
{

    public class RabbitMQHelper
    {
        public static ConnectionFactory _connectionFactory = null;
        private static string HostName = "127.0.0.1";
        private static string UserName = "guest";
        private static string Password = "guest";
        /// <summary>
        /// 构造函数
        /// </summary>
        static RabbitMQHelper()
        {
            _connectionFactory = new ConnectionFactory()
            {
                HostName = HostName,
                UserName = UserName,
                Password = Password,
            };
        }

        #region 消息入列
        /// <summary>
        /// 写入消息队列
        /// </summary>
        /// <typeparam name="T">消息类型</typeparam>
        /// <param name="message">消息内容</param>
        /// <param name="qure">交换器</param>
        /// <param name="durable">true、false true：服务器重启会保留下来Exchange。警告：仅设置此选项，不代表消息持久化。即不保证重启后消息还在</param>
        public static void SendMessage<T>(T message, string qure, bool durable)
        {
            using (var connection = _connectionFactory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(qure, durable, false, false, null);
                    var properties = channel.CreateBasicProperties();
                    properties.SetPersistent(true);
                    var IsList = message.GetType().IsGenericType;
                    if (IsList)
                    {
                        foreach (var item in message as List<T>)
                        {
                            var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item));//序列化为json字符串,存储为json字符
                            channel.BasicPublish("", qure, properties, body);
                        }
                    }
                    else
                    {
                        var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));//序列化为json字符串,存储为json字符
                        channel.BasicPublish("", qure, properties, body);

                    }
                }
            }
        }
        #endregion
    }
}
